/*
 * handle_accept.c
 *
 *  Created on: 2009-5-5
 *      Author: tian
 */

#include"tcpipsim.h"
#include<string.h>

void handle_accept(msg *pmsg){
	sockmsg retmsg;
	memset(&retmsg,0,sizeof(sockmsg));
	struct tcpcb *ptcpcb=get_tcpcb_by_sock(pmsg->pid,pmsg->sock);
	if(ptcpcb==NULL){
		retmsg.mtype=pmsg->sock;
		retmsg.ret=-1;
		if(msgsnd(pmsg->msgqid,&retmsg,sizeof(sockmsg)-sizeof(long),IPC_NOWAIT)<0){
			fprintf(stderr,"can not send message to application layer\n");
			return;
		}
	}
	else{
		if(ptcpcb->q2beg==ptcpcb->q2end){
			retmsg.mtype=pmsg->sock;
			retmsg.ret=-2;
			if(msgsnd(pmsg->msgqid,&retmsg,sizeof(sockmsg)-sizeof(long),IPC_NOWAIT)<0){
				fprintf(stderr,"can not send message to application layer\n");
				return;
			}
		}
		else{
			struct tcpcb * p=get_tcpcb(&(ptcpcb->queue2[ptcpcb->q2beg]));
			if(p==NULL){
				retmsg.ret=-1;
			}
			else{
				p->sock=atoi(pmsg->buf);
				retmsg.ret=p->sock;
				retmsg.sock_addr=p->sock_addr;
				ptcpcb->q2beg=(ptcpcb->q2beg++)%ptcpcb->q2num;
			}
			retmsg.mtype=pmsg->sock;
			if(msgsnd(ptcpcb->msgqid,&retmsg,sizeof(sockmsg)-sizeof(long),IPC_NOWAIT)<0){
				perror("can not communicate with application layer");
				return;
			}
		}
	}
}
